import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';

export async function GET(request: NextRequest) {
    try {
        const { searchParams } = new URL(request.url);
        const filePath = searchParams.get('path');

        if (!filePath) {
            return NextResponse.json(
                { success: false, error: '文件路径参数是必需的' },
                { status: 400 }
            );
        }

        const baseDir = path.join(process.cwd(), 'storage');
        const targetPath = path.join(baseDir, filePath);

        const normalizedTargetPath = path.normalize(targetPath);
        const normalizedBaseDir = path.normalize(baseDir);

        if (!normalizedTargetPath.startsWith(normalizedBaseDir)) {
            return NextResponse.json(
                { success: false, error: '无效的文件路径' },
                { status: 400 }
            );
        }

        try {
            // 检查文件是否存在
            const stats = await fs.stat(targetPath);
            
            if (!stats.isFile()) {
                return NextResponse.json(
                    { success: false, error: '指定路径不是文件' },
                    { status: 400 }
                );
            }

            // 读取文件内容
            const fileBuffer = await fs.readFile(targetPath);
            
            // 根据文件扩展名设置正确的Content-Type
            const ext = path.extname(filePath).toLowerCase();
            let contentType = 'application/octet-stream';
            
            switch (ext) {
                case '.glb':
                    contentType = 'model/gltf-binary';
                    break;
                case '.gltf':
                    contentType = 'model/gltf+json';
                    break;
                case '.json':
                    contentType = 'application/json';
                    break;
                case '.png':
                    contentType = 'image/png';
                    break;
                case '.jpg':
                case '.jpeg':
                    contentType = 'image/jpeg';
                    break;
                case '.hdr':
                    contentType = 'image/vnd.radiance';
                    break;
            }

            // 返回文件内容
            return new NextResponse(fileBuffer as unknown as ArrayBuffer, {
                headers: {
                    'Content-Type': contentType,
                    'Content-Length': stats.size.toString(),
                    'Cache-Control': 'public, max-age=31536000', // 缓存1年
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'GET',
                    'Access-Control-Allow-Headers': 'Content-Type',
                },
            });
        } catch (error) {
            if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
                return NextResponse.json(
                    { success: false, error: '文件不存在' },
                    { status: 404 }
                );
            }
            throw error;
        }
    } catch (error) {
        console.error('Error serving file:', error);
        return NextResponse.json(
            { success: false, error: '文件服务失败' },
            { status: 500 }
        );
    }
} 